﻿#ifndef SERVERTHREAD_H
#define SERVERTHREAD_H

#include "server_class_def.h"
#include "valdefs.h"
#include "json/json.h"

#include <string>
#include <QThread>
#include <vector>
#include <map>

class ServerThread : public QThread
{
    Q_OBJECT
public:
    explicit ServerThread(ServerWindow *cw, QObject *parent = nullptr, std::string server_config_filepath = "C:\\temp\\server_config.json");
    ~ServerThread(void);
protected:
    void run(void)override;

private:
    ServerWindow *sw_;
    std::string rsa_pubkey_;
    std::string rsa_prikey_;
    bool flag_softly_exit_;
    std::string server_config_filepath_;
    int client_socket_fd_;
    int server_socket_fd_;
    struct ServerConfig server_config_;
    std::vector<char*> risked_cstr_ptrs_;
    std::map<unsigned long long, struct RegisteredClientData> registered_client_map_;
    std::map<unsigned long long, struct OnlineClientData> online_client_map_;

    void InitConn(void);
    void HandleMsg(std::string encrypted_msg, unsigned int client_socket_fd);
    void GenerateRSAKey(void);
    bool SaveServerConfig(void);
    bool ReadServerConfig(void);
    void SetServerConfigFilepath(std::string filepath);
    void TryToCloseNetwork(void);
    void ShowConfig(void);
    void HandleMsgType(Json::Value json, unsigned int client_socket_fd);
    void HandleRegReq(Json::Value json, unsigned int client_socket_fd);
    void HandleUnregReq(Json::Value json, unsigned int client_socket_fd);
    void HandlePubkeyReq(Json::Value json, unsigned int client_socket_fd);
    void HandleLogin(Json::Value json, unsigned int client_socket_fd);
    void HandleLogout(Json::Value json, unsigned int client_socket_fd);
    void HandleLoginRefresh(Json::Value json, unsigned int client_socket_fd);
    void HandleClientPubkeyChange(Json::Value json, unsigned int client_socket_fd);
    bool FindIdInRegisteredClients(unsigned long long id, struct RegisteredClientData &ret);
    bool FindIdInOnlineClients(unsigned long long id, struct OnlineClientData &ret);


public slots:
    void OnRequestExit(void);
    void OnAboutFinished(void);
    void OnWindowShowMsg(QString msg);
    void OnChangeConfig(struct ServerConfig config);
    void OnSoftRestart(void);
    void OnAppQuit(void);

signals:
    void SignalRequestExit(void);
    void SignalWindowShowMsg(QString msg);
    void SignalChangeConfig(struct ServerConfig config);
    void SignalSoftRestart(void);
};

#endif // SERVERTHREAD_H
